package com.jeesite.modules.car.web;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.modules.car.entity.Image;
import com.jeesite.modules.car.service.ImageService;
import com.jeesite.modules.general.CosUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.car.entity.Car;
import com.jeesite.modules.car.service.CarService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 车辆详情Controller
 * @author qu
 * @version 2023-12-11
 */
@Controller
@RequestMapping(value = "${adminPath}/car/car")
public class CarController extends BaseController {

	@Autowired
	private CarService carService;

	@Autowired
	private ImageService imageService;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Car get(String carId, boolean isNewRecord) {
		return carService.get(carId, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("car:car:view")
	@RequestMapping(value = {"list", ""})
	public String list(Car car, Model model) {
		model.addAttribute("car", car);
		return "modules/car/carList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("car:car:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<Car> listData(Car car, HttpServletRequest request, HttpServletResponse response) {
		car.setPage(new Page<>(request, response));
		Page<Car> page = carService.findPage(car);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("car:car:view")
	@RequestMapping(value = "form")
	public String form(Car car, Model model) {
		model.addAttribute("car", car);
		return "modules/car/carForm";
	}
	/**
	 * 编辑车辆信息
	 */
	@RequiresPermissions("car:car:view")
	@RequestMapping(value = "formEdit")
	public String formEdit(Car car, Model model) {
		car.setSellPrice(car.getSellPrice()/100);
		model.addAttribute("car", car);
		return "modules/car/carFormEdit";
	}

	/**
	 * 编辑车辆图片
	 */
	@RequiresPermissions("car:car:view")
	@RequestMapping(value = "FormImg")
	public String carFormImg(Car car, Model model) {
		Image imag =new Image();
		imag.setForeignId(car.getCarId());
		List<Image> list = imageService.findList(imag);
		Map<String, List<Image>> collect = list.stream().collect(Collectors.groupingBy(Image::getImageType));
		car.setCarousel(collect.get("0"));
		car.setDetail(collect.get("1"));
		model.addAttribute("car", car);
		model.addAttribute("baseUrl", CosUtil.URL);
		return "modules/car/carFormImg";
	}

	/**
	 * 编辑车辆基本数据
	 */
	@RequiresPermissions("car:car:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Car car) {
		car.setSellPrice(car.getSellPrice()*100);
		carService.update(car);
		return renderResult(Global.TRUE, text("保存车辆详情成功！"));
	}

	/**
	 * 保存车辆基本信息及图片数据
	 */
	@RequiresPermissions("car:car:edit")
	@PostMapping(value = "saveCar")
	@ResponseBody
	public String saveCar(@RequestParam(value = "files", required = false) MultipartFile[] files, @Validated Car car) {
		if (!Objects.isNull(files)) {
			List<Image> list= new ArrayList<>();
			for (MultipartFile file : files) {
				String[] name = (FilenameUtils.getName(file.getOriginalFilename())).split("_");
				if("cover".equals(name[0])){
					JSONObject result = CosUtil.uploadFile(file, "", "car/cover");
					if(!result.getBoolean("result")){
						car.setCoverUrl(result.getString("fileName2"));
					}else {
						return renderResult(Global.TRUE, text("封面图片上传失败！"));
					}
				}
				if("carousel".equals(name[0])){
					JSONObject result = CosUtil.uploadFile(file, "", "car/carousel");
					if(!result.getBoolean("result")){
						Image image = new Image();
						image.setImageUrl(result.getString("fileName2"));
						image.setImageType("0");
						list.add(image);
					}else {
						return renderResult(Global.TRUE, text("轮播图片上传失败！"));
					}
				}
				if("detail".equals(name[0])){
					JSONObject result = CosUtil.uploadFile(file, "", "car/detail");
					if(!result.getBoolean("result")){
						Image image = new Image();
						image.setImageUrl(result.getString("fileName2"));
						image.setImageType("1");
						list.add(image);
					}else {
						return renderResult(Global.TRUE, text("详情图片上传失败！"));
					}
				}
			}
			car.setSellPrice(car.getSellPrice()*100);
			carService.insert(car);
			list.forEach(item->{
				item.setForeignId(car.getCarId());
			});
			imageService.saveImg(list);
			return renderResult(Global.TRUE, text("保存数据成功！"));
		} else {
			return renderResult(Global.FALSE, text("图片未上传！"));
		}
	}

	/**
	 * 保存车辆图片信息
	 */
	@RequiresPermissions("car:car:edit")
	@RequestMapping(value = "saveFormImg")
	@ResponseBody
	public String saveFormImg(@RequestParam(value = "files", required = false) MultipartFile[] files, String carId, String delCover, String delCarousel, String delDetail) {
		//删除旧数据
		if(!"".equals(delCover)){
			CosUtil.delCOSFile(delCover, "car/cover");
		}
		List<String> del = new ArrayList<>();//轮播详情图片记录ids
		List<String> del2 = new ArrayList<>();//对象存储图片name
		JSONArray carousel = JSONArray.parseArray(delCarousel);
		for (int i = 0; i < carousel.size(); i++) {
			JSONObject jsonObject = carousel.getJSONObject(i);
			del.add(jsonObject.get("id").toString());
			del2.add(jsonObject.get("name").toString());
		}
		if (del2.size()>0) {
			CosUtil.delCOSFile(del2.stream().collect(Collectors.joining(",")), "car/carousel");
		}
		JSONArray detail = JSONArray.parseArray(delDetail);
		List<String> del3 = new ArrayList<>();
		for (int i = 0; i < detail.size(); i++) {
			JSONObject jsonObject = detail.getJSONObject(i);
			del.add(jsonObject.get("id").toString());
			del3.add(jsonObject.get("name").toString());
		}
		if (del3.size()>0) {
			CosUtil.delCOSFile(del3.stream().collect(Collectors.joining(",")), "car/detail");
		}
		//删除image表记录
		if (del.size()>0) {
			imageService.deleteImg(del);
		}
		//保存新添加的图片信息
		if (!Objects.isNull(files)) {
			Car car = new Car();
			car.setCarId(carId);
			List<Image> list= new ArrayList<>();
			for (MultipartFile file : files) {
				String[] name = (FilenameUtils.getName(file.getOriginalFilename())).split("_");
				if("cover".equals(name[0])){
					JSONObject result = CosUtil.uploadFile(file, "", "car/cover");
					if(!result.getBoolean("result")){
						car.setCoverUrl(result.getString("fileName2"));
					}else {
						return renderResult(Global.TRUE, text("封面图片上传失败！"));
					}
				}
				if("carousel".equals(name[0])){
					JSONObject result = CosUtil.uploadFile(file, "", "car/carousel");
					if(!result.getBoolean("result")){
						Image image = new Image();
						image.setForeignId(carId);
						image.setImageUrl(result.getString("fileName2"));
						image.setImageType("0");
						list.add(image);
					}else {
						return renderResult(Global.TRUE, text("轮播图片上传失败！"));
					}
				}
				if("detail".equals(name[0])){
					JSONObject result = CosUtil.uploadFile(file, "", "car/detail");
					if(!result.getBoolean("result")){
						Image image = new Image();
						image.setForeignId(carId);
						image.setImageUrl(result.getString("fileName2"));
						image.setImageType("1");
						list.add(image);
					}else {
						return renderResult(Global.TRUE, text("详情图片上传失败！"));
					}
				}
			}
			carService.update(car);
			imageService.saveImg(list);
		}
		return renderResult(Global.TRUE, text("保存数据成功！"));
	}
	
	/**
	 * 删除、停用、启用数据
	 */
	@RequiresPermissions("car:car:edit")
	@RequestMapping(value = "updateStatus")
	@ResponseBody
	public String updateStatus(Car car) {
		carService.update(car);
		return renderResult(Global.TRUE, text("操作成功！"));
	}
	
}